<template>
    <div class="search">
        <el-autocomplete 
        class="search-input"
        v-model="value"
        :fetch-suggestions="fetchHistorySuggestion"
        :maxlength="20"
        >
            <div 
            v-if="item.type === 'group-title'"
            class="group-title"
            slot-scope="{ item }"
            @click.prevent.stop
            >
                {{item.value}}
            </div>

            <div 
            class="suggest-item" 
            slot-scope="{ item }"
            v-else-if="item.id"
            >
                <div class="value">{{ item.value }}</div>
            </div>

            <div 
            class="history-item" 
            slot-scope="{ item }"
            v-else
            >
                <div class="value">{{ item.value }}</div>
                <span class="icon">
                    <i 
                        class="el-icon-close"
                        @click.stop="delTheHistory(item)"
                    ></i>
                </span>
            </div>

            <el-button 
                type="primary"
                slot="append"
                icon="el-icon-search"
                @click="clickHandler"
            ></el-button>
        </el-autocomplete>
    </div>
</template>

<script>

export default {
    data() {
        return {
            value: '',
            questionVisible: false,

            historyList: [],
            suggestList: [],
        };
    },
    methods: {
        /**
         * 搜索
         */
        clickHandler() {
            this.updateLocalHistory();

            this.$get(`${this.$store.state.api.webUrl}/search/log.json`, {
                title: this.value,
            }, data => {
                var title = encodeURIComponent(this.value);

                if (/^\/search/.test(this.$route.path)) {
                    window.location.assign(`${this.$route.path}?title=${title}`);
                } else {
                    window.location.assign(`/search?title=${title}`);
                }
            });
        },
        /**
         * 更新搜索记录 
         */
        updateLocalHistory() {
            var searchHistory = this.historyList,
                existedIndex = searchHistory.indexOf(this.value);

            if (existedIndex > -1) {
                // 历史记录里有的话，就把历史记录里的去掉
                searchHistory.splice(existedIndex, 1);
            }

            // 将搜索内容加入历史记录里
            searchHistory.unshift(this.value);

            // 仅保留最新的5条记录；
            searchHistory = searchHistory.slice(0, 5);

            setLocal({
                'search-history': searchHistory,
            });
        },
        delTheHistory(item) {
            var value = item.value,
                searchHistory = this.historyList,
                existedIndex = searchHistory.indexOf(value);

            searchHistory.splice(existedIndex, 1);
            
            this.historyList = searchHistory;

            setLocal({
                'search-history': searchHistory,
            });
        },
        /**
         * 打开添加问题dialog
         */
        dialogShow() {
            this.questionVisible = true;
        },
        /**
         * 匹配历史记录
         */
        fetchHistorySuggestion(queryString, cb) {
            var restaurants = this.historyList;
            var results = queryString ? restaurants.filter(text => text !== queryString) : restaurants;

            results = [
                {
                    type: 'group-title',
                    value: '热门推荐',
                    disabled: true,
                },
                ...this.suggestList.map(item => {
                    return {
                        value: item.dicname,
                        id: item.id,
                    };
                }),
                {
                    type: 'group-title',
                    value: '搜索历史',
                    disabled: true,
                },
                ...results.map(text => {
                    return {
                        value: text,
                    };
                }),
            ];
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        /**
         * 获取字典中的搜索推荐
         */
        querySearchKeyInDoc() {
            // this.$get(`${this.$store.state.api.webUrl}/common/dictbytype.json`, {
            //     type: 'search-keyword',
            // }, data => {
            //     var length = data.length,
            //         random = Math.floor(Math.random() * length);

            //     this.value = data[random].dicname;

            //     this.suggestList = data;
            // });
        },
    },
    mounted() {
        var title = this.$route.query.title;

        if (title) {
            this.value = title;
        } else {
            this.querySearchKeyInDoc();
        }

        this.historyList = getLocal('search-history') || [];
    }
}
</script>

<style lang="scss" scoped>
    @import '@css/var.scss';

    .search{
        float: left;
        margin-top: 18px;
        margin-left: 70px;

        .search-input{
            width: 324px;
            vertical-align: middle;

            ::v-deep {
                .el-input__inner{
                    color: #999999;
                    border-right: none;
                    height: 34px;
                    font-size: 12px;

                    &:focus + .el-input-group__append{
                        border-color: $primaryColor;
                    }
                }

                .el-input-group__append{
                    background-color: $primaryColor;
                    border-color: $primaryColor;
                    color: white;
                    font-size: 16px;
                    padding: 0 16px;
                    transition: .3s border-color;
                }
            }
        }
    }

    .group-title{
        font-size: 12px;
        color: $infoColor;
        line-height: 30px;
        margin: 0 -20px;
        padding: 0 20px;
        position: relative;

        &:after{
            content: '';
            display: block;
            height: 1px;
            background: $infoColor2;
            position: absolute;
            left: 20px;
            right: 20px;
            bottom: 0;
        }
    }

    .history-item{
        display: flex;

        .value{
            flex: 1;
        }

        .icon{
            &:hover{
                color: $primaryColor;
            }
        }
    }
</style>